package com.ruoyi.system.service.impl;

import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysSchoolClassMapper;
import com.ruoyi.system.mapper.SysSchoolScoreMapper;
import com.ruoyi.system.service.ISysSchoolScoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.domain.SysSchoolScore;
import com.ruoyi.system.mapper.SysSchoolStudentMapper;
import com.ruoyi.system.domain.SysSchoolStudent;
import com.ruoyi.system.service.ISysSchoolStudentService;

/**
 * 学员信息Service业务层处理
 * 
 * @author 杨皓焜
 * @date 2021-01-31
 */
@Service
public class SysSchoolStudentServiceImpl implements ISysSchoolStudentService 
{
    private static final Logger log = LoggerFactory.getLogger(SysSchoolStudentServiceImpl.class);
    @Autowired
    private SysSchoolStudentMapper sysSchoolStudentMapper;
    @Autowired
    private SysSchoolScoreMapper sysSchoolScoreMapper;
    @Autowired
    private SysSchoolClassMapper sysSchoolClassMapper;
    @Autowired
    private ISysSchoolScoreService sysSchoolScoreService;

    /**
     * 查询学员信息
     * 
     * @param id 学员信息ID
     * @return 学员信息
     */
    @Override
    public SysSchoolStudent selectSysSchoolStudentById(Long id)
    {
        return sysSchoolStudentMapper.selectSysSchoolStudentById(id);
    }

    /**
     * 查询学员信息列表
     * 
     * @param sysSchoolStudent 学员信息
     * @return 学员信息
     */
    @Override
    public List<SysSchoolStudent> selectSysSchoolStudentList(SysSchoolStudent sysSchoolStudent)
    {
        return sysSchoolStudentMapper.selectSysSchoolStudentList(sysSchoolStudent);
    }

    /**
     * 新增学员信息
     * 
     * @param sysSchoolStudent 学员信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSysSchoolStudent(SysSchoolStudent sysSchoolStudent)
    {
        int rows = sysSchoolStudentMapper.insertSysSchoolStudent(sysSchoolStudent);
        insertSysSchoolScore(sysSchoolStudent);
        return rows;
    }

    /**
     * 修改学员信息
     * 
     * @param sysSchoolStudent 学员信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSysSchoolStudent(SysSchoolStudent sysSchoolStudent)
    {
        /*
        for (SysSchoolScore score : scores) {

            sysSchoolScoreMapper.insertSysSchoolScore(score);
        }*/

        insertSysSchoolScore(sysSchoolStudent);
        return sysSchoolStudentMapper.updateSysSchoolStudent(sysSchoolStudent);
    }


    /**
     * 批量删除学员信息
     * 
     * @param ids 需要删除的学员信息ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSysSchoolStudentByIds(Long[] ids)
    {
        sysSchoolStudentMapper.deleteSysSchoolScoreByStudentIds(ids);
        return sysSchoolStudentMapper.deleteSysSchoolStudentByIds(ids);
    }

    /**
     * 删除学员信息信息
     * 
     * @param id 学员信息ID
     * @return 结果
     */
    @Override
    public int deleteSysSchoolStudentById(Long id)
    {
        sysSchoolStudentMapper.deleteSysSchoolScoreByStudentId(id);
        return sysSchoolStudentMapper.deleteSysSchoolStudentById(id);
    }

    @Override
    public void deleteSysSchoolStudentByClassIds(Long[] ids) {
        List<Long> studentIds = new ArrayList<>();
        for (Long id : ids) {
            List<SysSchoolStudent> sysSchoolStudents = sysSchoolStudentMapper.selectSysSchoolStudentByClassId(id);
            sysSchoolClassMapper.deleteSysSchoolStudentByClassId(id);
            for (SysSchoolStudent sysSchoolStudent : sysSchoolStudents) {
                Long studentId = sysSchoolStudent.getId();
                studentIds.add(studentId);
            }
        }
        studentIds.forEach(id -> sysSchoolStudentMapper.deleteSysSchoolScoreByStudentId(id));

    }

    /**
     * 导入学员数据
     *
     * @param studentList 学员数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importStudent(List<SysSchoolStudent> studentList, boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(studentList) || studentList.size() == 0)
        {
            throw new CustomException("导入学员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysSchoolStudent student : studentList)
        {
            try
            {
                // 验证是否存在这个用户
                SysSchoolStudent s = sysSchoolStudentMapper.selectSysSchoolStudentByStudenName(student.getStudentName());
                if (StringUtils.isNull(s))
                {
                    student.setCreateBy(operName);
                    this.insertSysSchoolStudent(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + student.getStudentName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    student.setUpdateBy(operName);
                    this.updateSysSchoolStudent(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + student.getStudentName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + student.getStudentName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + student.getStudentName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int updateSysSchoolStudents(List<SysSchoolStudent> sysSchoolStudents) {
        try {
            for (SysSchoolStudent sysSchoolStudent : sysSchoolStudents) {
                insertSysSchoolScore(sysSchoolStudent);
                sysSchoolStudentMapper.updateSysSchoolStudent(sysSchoolStudent);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return 1;
    }

    @Override
    public List<SysSchoolStudent> selectSysSchoolStudentByClassId(Long id) {
        return sysSchoolStudentMapper.selectSysSchoolStudentByClassId(id);
    }

    @Override
    public void editScore(SysSchoolStudent student) {
        List<SysSchoolScore> scores = student.getSysSchoolScoreList();
        for (SysSchoolScore score : scores) {
            if (score.getCreateBy() != null ) {
                SysSchoolScore schoolScore = sysSchoolScoreMapper.findByTime(score.getCreateTime());
                if (!score.getRemark().equals(schoolScore.getRemark())) {
                    score.setId(schoolScore.getId());
                    score.setUpdateBy(SecurityUtils.getUsername());
                    sysSchoolScoreService.updateSysSchoolScore(score);
                }
            }else if (score.getCreateBy() == null){
                score.setId(null);
                score.setStudentId(student.getId());
                score.setCreateBy(SecurityUtils.getUsername());
                sysSchoolScoreService.insertSysSchoolScore(score);
            }
        }
    }

    /**
     * 新增操行分信息信息
     * 
     * @param sysSchoolStudent 学员信息对象
     */
    public void insertSysSchoolScore(SysSchoolStudent sysSchoolStudent)
    {
        Long id = sysSchoolStudent.getId();
        List<SysSchoolScore> sysSchoolScoreList = sysSchoolScoreMapper.selectSysSchoolScoreByStudentId(id);
        sysSchoolStudentMapper.deleteSysSchoolScoreByStudentId(sysSchoolStudent.getId());
        if (StringUtils.isNotNull(sysSchoolScoreList))
        {
            List<SysSchoolScore> list = new ArrayList<SysSchoolScore>();
            for (SysSchoolScore sysSchoolScore : sysSchoolScoreList)
            {
                sysSchoolScore.setStudentId(id);
                list.add(sysSchoolScore);
            }
            if (list.size() > 0)
            {
                sysSchoolStudentMapper.batchSysSchoolScore(list);
            }
        }
    }
}
